package section

import (
	"context"

	"mall/service/backend/common/errorx"
	"mall/service/backend/common/i18n"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	"github.com/zeromicro/go-zero/core/logx"
)

type DetachProductFromSectionLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewDetachProductFromSectionLogic(ctx context.Context, svcCtx *svc.ServiceContext) *DetachProductFromSectionLogic {
	return &DetachProductFromSectionLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *DetachProductFromSectionLogic) DetachProductFromSection(in *backend.DetachIDsReq) (*backend.BaseResp, error) {
	if in.Id == nil || *in.Id == 0 || (len(in.BrandIds) == 0 && len(in.CategoryIds) == 0 && len(in.Ids) == 0) {
		return nil, errorx.NewInvalidArgumentError("common.validationError")
	}

	if len(in.Ids) > 0 {
		var ids []any
		for _, id := range in.Ids {
			if id > 0 {
				ids = append(ids, id)
			}
		}

		if len(ids) > 0 {
			filterMap := make(map[string]map[string][]any)
			filterMap[model.SectionProductRelationshipColumns.SectionID] = map[string][]any{
				"equalTo": {*in.Id},
			}
			filterMap[model.SectionProductRelationshipColumns.ProductID] = map[string][]any{
				"in": ids,
			}
			err := l.svcCtx.Section.DetachProductFromSection(l.ctx, nil, filterMap)
			if err != nil {
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}
		}

		return &backend.BaseResp{
			Msg: i18n.DeleteSuccess,
		}, nil
	}

	if len(in.BrandIds) > 0 {
		var ids []any
		for _, id := range in.BrandIds {
			if id > 0 {
				ids = append(ids, id)
			}
		}

		if len(ids) > 0 {
			filterMap := make(map[string]map[string][]any)
			filterMap[model.SectionProductRelationshipColumns.SectionID] = map[string][]any{
				"equalTo": {*in.Id},
			}
			filterMap[model.SectionProductRelationshipColumns.BrandID] = map[string][]any{
				"in": ids,
			}
			err := l.svcCtx.Section.DetachProductFromSection(l.ctx, nil, filterMap)
			if err != nil {
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}
		}

		return &backend.BaseResp{
			Msg: i18n.DeleteSuccess,
		}, nil
	}

	if len(in.CategoryIds) > 0 {
		var ids []any
		for _, id := range in.CategoryIds {
			if id > 0 {
				ids = append(ids, id)
			}
		}

		if len(ids) > 0 {
			filterMap := make(map[string]map[string][]any)
			filterMap[model.SectionProductRelationshipColumns.SectionID] = map[string][]any{
				"equalTo": {*in.Id},
			}
			filterMap[model.SectionProductRelationshipColumns.CategoryID] = map[string][]any{
				"in": ids,
			}
			err := l.svcCtx.Section.DetachProductFromSection(l.ctx, nil, filterMap)
			if err != nil {
				return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
			}
		}

		return &backend.BaseResp{
			Msg: i18n.DeleteSuccess,
		}, nil
	}

	return &backend.BaseResp{}, nil
}
